// components/Timeline.tsx
import React, { useState, useEffect, useRef } from 'react';
import styles from './Timeline.module.css';
import { TimelineEvent } from './schemas';

const HighlightMarker = () => (
  <div className={styles.marker}>
    <div className={styles.markerLine}></div>
    <div className={styles.markerDot}></div>
  </div>
);

const TimelineItem = ({ 
  event, 
  isActive, 
  onClick 
}: { 
  event: TimelineEvent;
  isActive: boolean;
  onClick: () => void;
}) => (
  <div 
    className={`${styles.timelineItem} ${isActive ? styles.active : ''}`}
    onClick={onClick}
  >
    <div className={styles.time}>{event.time}</div>
    <div className={styles.title}>{event.title}</div>
  </div>
);

const Timeline = ({
  events,
  onActiveEventChange
}: {
  events: TimelineEvent[];
  onActiveEventChange: (event: TimelineEvent) => void;
}) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [activeEvent, setActiveEvent] = useState<TimelineEvent>(events[0]);

  const handleScroll = () => {
    if (!containerRef.current) return;

    const container = containerRef.current;
    const markerPosition = container.offsetHeight / 2;
    const items = container.querySelectorAll(`.${styles.timelineItem}`);

    items.forEach((item, index) => {
      const rect = item.getBoundingClientRect();
      const containerRect = container.getBoundingClientRect();
      
      if (
        rect.top <= containerRect.top + markerPosition && 
        rect.bottom >= containerRect.top + markerPosition
      ) {
        setActiveEvent(events[index]);
      }
    });
  };

  const handleClick = (event: TimelineEvent) => {
    const item = document.getElementById(event.id);
    if (item && containerRef.current) {
      const container = containerRef.current;
      const markerPosition = container.offsetHeight / 2;
      const targetPosition = 
        item.offsetTop - markerPosition + item.offsetHeight / 2;
      
      container.scrollTo({
        top: targetPosition,
        behavior: 'smooth'
      });
      setActiveEvent(event);
    }
  };

  useEffect(() => {
    const container = containerRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll);
      return () => container.removeEventListener('scroll', handleScroll);
    }
  }, []);

  useEffect(() => {
    onActiveEventChange(activeEvent);
  }, [activeEvent, onActiveEventChange]);

  return (
    <div className={styles.timelineContainer}>
      <div 
        ref={containerRef}
        className={styles.timelineScrollContainer}
      >
        {events.map(event => (
          <div
            key={event.id}
            className={styles.timelineItemWrapper}
            id={event.id}
          >
            <HighlightMarker />
            <TimelineItem
              event={event}
              isActive={activeEvent.id === event.id}
              onClick={() => handleClick(event)}
            />
          </div>
        ))}
      </div>
    </div>
  );
};

export default Timeline;